import { AxiosResponse, InternalAxiosRequestConfig } from './types'
import { ElMessage } from 'element-plus'
import qs from 'qs'
import { SUCCESS_CODE, TRANSFORM_REQUEST_DATA } from '@/constants'
import { objToFormData } from '@/utils'
import { useUserStore } from '@/store/modules/user'
import { AxiosError } from 'axios'

const defaultRequestInterceptors = (config: InternalAxiosRequestConfig) => {
  if (
    config.method === 'post' &&
    config.headers['Content-Type'] === 'application/x-www-form-urlencoded'
  ) {
    config.data = qs.stringify(config.data)
  } else if (
    TRANSFORM_REQUEST_DATA &&
    config.method === 'post' &&
    config.headers['Content-Type'] === 'multipart/form-data'
  ) {
    config.data = objToFormData(config.data)
  }
  if (config.method === 'get' && config.params) {
    let url = config.url as string
    url += '?'
    const keys = Object.keys(config.params)
    for (const key of keys) {
      if (
        // 禁止提交的get参数类型
        config.params[key] !== void 0 &&
        config.params[key] !== null &&
        config.params[key] !== ''
      ) {
        url += `${key}=${encodeURIComponent(config.params[key])}&`
      }
    }
    url = url.substring(0, url.length - 1)
    config.params = {}
    config.url = url
  }
  return config
}

const defaultResponseInterceptors = (response: AxiosResponse) => {
  if (response?.config?.responseType === 'blob') {
    // 如果是文件流，直接过
    return response
  } else if (SUCCESS_CODE.includes(response?.data?.code)) {
    return response.data
  } else {
    ElMessage.error(response?.data?.message || '后端接口无返回内容')
  }
}

const defaultResponseErrorInterceptors = (error: AxiosError) => {
  let { message } = error
  const userStore = useUserStore()
  switch (error.response?.status) {
    case 400:
      message = '请求错误'
      break
    case 401:
      // 强制要求重新登录，因账号已冻结，账号已过期，手机号码错误，刷新token无效等问题导致
      userStore.logout()
      message = '认证已过期，请重新登录'
      break
    case 403:
      // 强制要求重新登录，因无系统权限，而进入到系统访问等问题导致
      userStore.logout()
      message = '鉴权失败，请重新登录'
      break
    case 404:
      message = `请求地址出错: ${error.response?.config.url}`
      break
    case 408:
      message = '请求超时'
      break
    case 500:
      message = '服务器内部错误'
      break
    case 501:
      message = '服务未实现'
      break
    case 502:
      message = '网关错误'
      break
    case 503:
      message = '服务不可用'
      break
    case 504:
      message = '网关超时'
      break
    case 505:
      message = 'HTTP版本不受支持'
      break
    default:
      break
  }
  ElMessage.error(message)
  return Promise.reject(error)
}

export { defaultResponseInterceptors, defaultRequestInterceptors, defaultResponseErrorInterceptors }
